package com.mrogrape.notepad.ui.library;

import java.io.Serializable;
import java.util.LinkedList;
import java.util.List;

import com.mrogrape.util.StringUtils;

public class Library implements Serializable {

	/** serialVersionUID */
	private static final long serialVersionUID = 1L;

	String name;
	List<Inclusion> includes;

	public Library(String name) {

		if(StringUtils.isEmpty(name)){
			throw new IllegalArgumentException("Name cannot be null.");
		}

		this.name = name;
		this.includes = new LinkedList<Inclusion>();
	}

	/**
	 * @param name the name to set
	 */
	public void setName(String name) {
		this.name = name;
	}

	/**
	 * @return the name
	 */
	public String getName() {
		return this.name;
	}

	/**
	 * 包含一个新的对象。
	 * 
	 * @param inclusion
	 */
	public void includeInclusion(Inclusion inclusion) throws IllegalArgumentException{

		if(inclusion == null){
			return;
		}

		if(this.finInclusion(inclusion.getName()) != null){
			throw new IllegalArgumentException("a inclusion named '" +inclusion.getName()+ "' alreay exist");
		}

		if(this.includes.contains(inclusion)){
			throw new IllegalArgumentException("inclusion alreay exist");
		}

		this.includes.add(inclusion);
	}

	/**
	 * 通过名字移除一个导入对象，这个对象必须是根对象。
	 * @param name
	 */
	public void removeInclusion(String name){
		Inclusion found = null;
		for(Inclusion inclusion : this.includes){
			if(inclusion.getName().equals(name)){
				found = inclusion;
				break;
			}
		}

		if(found != null){
			this.includes.remove(found);
		}
	}

	/**
	 * 获取所有的包含对象。
	 * 
	 * @return the includes
	 */
	public List<Inclusion> getIncludes() {

		if(this.includes ==null){
			this.includes = new LinkedList<Inclusion>();
		}
		return this.includes;
	}

	/**
	 * 通过名字查找导入对象。
	 * 
	 * @param name
	 * @return
	 */
	public Inclusion finInclusion(String name){

		for(Inclusion inclusion : this.includes){
			if(inclusion.getName().equals(name)){
				return inclusion;
			}
		}

		return null;
	}

	/** 
	 * {@inheritDoc}
	 * @see java.lang.Object#equals(java.lang.Object)
	 */
	@Override
	public boolean equals(Object obj) {

		if(obj == null){return false;}
		if(obj == this){return true;}
		if(obj instanceof Library){
			Library other = (Library) obj;
			if(StringUtils.isEquals(this.name, other.name)){
				return true;
			}
		}
		return false;
	}

	@Override
	public String toString() {
		return this.name;
	}
}
